package com.xinongbest;

import com.alibaba.fastjson.JSON;
import com.xinongbest.entity.GoodsDetail;
import org.junit.Test;
import redis.clients.jedis.Jedis;

public class JedisTester {

    /**
     * <h2>异常捕获，尽量使用try-resources</h2>
     * redis连接
     */
    @Test
    public void testConnRedisServer() {
        try (Jedis redis = new Jedis("10.1.1.181", 6379)) {
            redis.auth("0106");
            redis.select(1);
            redis.hset("emp:one", "name", "lemonwan");
            redis.hset("emp:one", "age", "29");
            System.out.println(redis.hgetAll("emp:one"));
            System.out.println("redis连接成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * <h2>测试序列化Java对象到Redis中存储</h2>
     */
    @Test
    public void testSerializeData() {
        try (Jedis redis = new Jedis("10.1.1.181")) {
            GoodsDetail detail = new GoodsDetail();
            detail.setDetailId(1000);
            detail.setDetailImage("www.baidu.com");
            detail.setDetailContent("商品详情");
            detail.setGoodsId(1100);
            detail.setGoodsBase(null);
            String goods = JSON.toJSONString(detail);
            redis.auth("0106");
            redis.set("goods:1000", goods);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * <h2>测试从Redis中获取Java对象序列化数据，并做反序列化操作</h2>
     */
    @Test
    public void testUnerializeData() {
        try (Jedis redis = new Jedis("10.1.1.181")) {
            redis.auth("0106");
            String goods = redis.get("goods:1000");
            GoodsDetail goodsDetail = JSON.parseObject(goods, GoodsDetail.class);
            System.out.println(goodsDetail.getDetailContent());
            System.out.println(goodsDetail.getDetailImage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
